#!/usr/bin/perl
 
use strict;
use warnings;

use Benchmark qw/cmpthese/;

sub decoupe_par_mot($$){
     my($nb_mots, $nb_parties) = @_;
     
     open (FD, "LesMysteresDeParis.txt") or die $!;
     read(FD, my $text, -s FD);
     
     my @words = split(/\s+/, $text);
     my $taille_parties;
     if($nb_parties > 0){
         $taille_parties = int(scalar(@words) /  $nb_parties );
     }else{
         warn '$nb_parties negatif ou nul (lib::SplitText::decoupe_par_mot)';
         exit;
     }
     if($taille_parties < $nb_mots ){
         $taille_parties = $nb_mots;
     }
     $nb_parties = int(scalar(@words) / $taille_parties);
     my @tab;
     for my $i (0..$nb_parties) {
         my $fin = 0;
         my $suite;
         my $k = int(rand($taille_parties - $nb_mots));
         my $l = $i*$taille_parties+$k;
         for($l..$l+$nb_mots-1){
             my $n = $_;
             if($words[$n]){
                 $suite .= " ".$words[$n];
                 $fin++;
             }
         }
         my @liste = ($l,$fin);
         my %case;
         $case{text} = $suite;
         $case{offset} = \@liste;
         $tab[$i] = \%case;
     }
     return \@tab;
 }

sub decoupe_par_chaine($$){
    my($len_str, $nb_req) = @_;
    open (FD, "LesMysteresDeParis.txt") or die $!;
    read(FD, my $text, -s FD);
    
    my $lentext = length($text);
    $len_str = $lentext if $lentext < $len_str;
    my $len = $lentext - $len_str;

    my $len_part = int($len/$nb_req);
    if ($len_part < $len_str){
        $len_part = $len_str;
    }
    $nb_req = int($len/$len_part);
    $nb_req = 1 unless $nb_req;

    my @tab;
    my $span1 = "";
    my $span2 = "";
    my $decalage = 0;
    for my $req (0..$nb_req-1){
        my $rand = int(rand($len_part - $len_str));
        $rand = 1 unless $rand; #cas ou rand=0;
        $rand += $req*$len_part;
        $decalage += length($span1.$span2);
        $rand += $decalage;
        my $part = substr($text, $rand, $len_str);
        $part =~ s/^.*?\s//m;
        $part =~ s/\s\p{IsWord}+$//m;
        $span1 = '<span class="requete" id="req_'.$req.'">';
        $span2 = '</span>';
        $text =~ s/(\Q$part\E)/$span1$1$span2/m;
        my $phrase = $1;
        my $case = {
            text   => $phrase,
            offset => $req,
        };
        push @tab, $case;
    }
    return (\@tab, $text);
}

# run the benchmark during 5 CPU seconds
cmpthese -5, {
    'par mot' => 'decoupe_par_mot(10,15)',
    'par chaine' => 'decoupe_par_chaine(10,15)',
};

